package thread;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.management.Query;

import dao.EventFieldsConditionDao;
import dao.FieldDao;
import model.Field;
import utils.msg.QueryResult;
import utils.msg.RecordModel;

public class SimpleQueryUtil {

	
	private static ResultSet rs = null;
	private static Statement statement = null;	 
	private static Connection dbConn=null;
	

	public static RecordModel queryFieldForCondition(String url, String driverName, String userName , String userPwd ,String dbName ,
			String table, String field, String condition,int timeSpan,String threshold,String querycontent,String createTime,String location, String locationValue){

		   RecordModel rm = null;
	         try { 
	    	   try {
				Class.forName(driverName);
			   } catch (ClassNotFoundException e) {
				e.printStackTrace();
			    } 
	           //dbConn = DriverManager.getConnection(url,"sa","sa123456");
	           dbConn = DriverManager.getConnection(url,userName,userPwd);
	           String strSql = "select " + querycontent + "," + createTime+","+location+ " from " + table + " where " + field + condition
						+ threshold + " and "+location+" = "+ locationValue  +" and "+createTime+" between dateadd(ms,-"+timeSpan+",getDate()) and  getDate()";
	           System.out.println("QueryUtil.queryFieldForCondition() strSql="+strSql);
				statement=dbConn.createStatement();
				rs = statement.executeQuery(strSql);
				
				
				while(rs.next()){
				    Timestamp timestamp=rs.getTimestamp(createTime);
                    Date date=new Date(timestamp.getTime());
					SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					rm=new RecordModel();
                    rm.setCreateDateTime(sdf1.format(date));
                    rm.setValue(rs.getDouble(field));
                    
                    rm.setLocation(rs.getString(location));
					break;
				}
	         }catch (SQLException sqlE) {
					sqlE.printStackTrace();
				} finally {
					 try {
						
		                 if (dbConn != null)
		                        dbConn.close();
		                 dbConn = null; 
		          } catch (Exception ex) {
		                 ex.printStackTrace();
		          } 
				}
	         return rm;
	}
}